// Cookie
function createCookie(name,value,days){if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));var expires="; expires="+date.toGMTString();}else{var expires="";}document.cookie=name+"="+value+expires+"; path=/";}function readCookie(name){var nameEQ=name+"=";var ca=document.cookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==' ') c=c.substring(1,c.length);if(c.indexOf(nameEQ)==0)return c.substring(nameEQ.length,c.length);}return null;}function eraseCookie(name){createCookie(name,"",-1);}

// Bottom of page
function allStuff() {
	var $window = $(window),
		$body = $(document.body),
		$dataAuthor = $('[data-author="Leo da Costa$"]'),
		$topLink = $('#gotop'),
		$checkerBox = $('#reader'),
		$viewPort = $('html, body'),
		$jumpLink = $('.local-permalink'),
		$ulSpy = $('ul.spy'),
		$blogStatus = $('#status'),
		$updateBoard = $blogStatus.find('.section'),
		$nav = $('#leodacosta'),
		$shockElem = $body.find('*'),
		$pageLoader = $('#page-loader'),
		$openFrame = $('.openFrame'),
		$myComments = $('#comments'),
		$commentBlock = $myComments.find('#cm_block'),
		$ansButton = $('.answer-this-comment'),
		$commentForm = $('#comment-form'),
		$commentEditor = $('#comment-editor'),
		$commentVideo = $myComments.find('.video'),
		$fiddleScreen = $('.jsfiddle-demo'),
		$myDescription = $('abbr, acronym'),
		$emoBar = $('#emobar'),
		$triggerDialog = $('.trigger-dialog'),
		$sidebarWrapper = $('#sidebar-wrapper'),
		$labelWidget = $sidebarWrapper.find('#Label1'),
		$togglePre = $('#togglePre'),
		$topRibbon = $('#top-ribbon'),
		$searchBox = $('#cse-search-box'),
		$subscribeForm = $topRibbon.find('#subscribeform'),
		$subscribeButton = $('.subscribe'),
		$closeForm = $('.closeform'),
		$opener = $('#openab'),
		$closer = $('#closeab'),
		$aboutPanel = $('#about'),
		$fadeElem = $('#cse-search-box, .ad-banner, #main, #reader, #alexa'),
		$slideElem = $('#header, #main-wrapper, #sidebar-wrapper, #ad-wrapper, .sidebarbox');

	// Some elements...
	$body.removeClass('init').append('<div id="alert-box" class="hidden"><div class="message"></div></div><span id="loadingtext"></span>').on("click", function() {
		$('.emoKey').remove();
	});
	var $alertBox = $('#alert-box'),
		$loadingText = $('#loadingtext');
	// Dialog
	function makeDialog(a,b,c) {
		var c = (b !== false) ? b : '',
			d = (b !== false) ? '<div class="button-group"><button class="close">'+c+'</button></div>' : '';
		$alertBox.fadeIn(600).children().css('width',c).html(a+d);
		if (b !== false) {
			$alertBox.on("click", ".close", function() {
				$alertBox.fadeOut();
			});
		}
	}
	// Tag Replace
	function tagReplace(a,b,c) {
		$(a).replaceWith(function() {
			return $(b+$(this).html()+c);
		});
	}
	// View my Profile
	function viewProfile() {
		$('#leodacosta li ul').slideUp();
		$topRibbon.stop().animate({top:-350}, 700, function() {
			$fadeElem.fadeOut(700, function() {
				$aboutPanel.slideDown(1000, function() {
					$(this).animate({width:"60%"}, 600);
				});
				$slideElem.slideUp(1000);
			});
		});
	}
	function hideProfile() {
		$fadeElem.fadeIn(700, function() {
			$topRibbon.stop().animate({top:0}, 600, function() {
				$aboutPanel.animate({width:"90%"}, 600, function() {
					$(this).slideUp(700);
				});
			});
		});
	}
	$opener.on("click", function() {
		if ($window.scrollTop() > 100) {
			$viewPort.stop().animate({scrollTop:0}, 'slow', viewProfile);
		} else {
			viewProfile();
		}
		return false;
	});
	$closer.on("click", function() {
		$slideElem.slideDown(1000, hideProfile);
		return false;
	});
	// Trigger dialog
	$emoBar.one("click", function() {
		makeDialog($(this).data('dialog'),'OK','370px');
	});
	$triggerDialog.on("click", function() {
		makeDialog($(this).data('dialog'),'Close','80%');
		return false;
	});
	// Sliding ribbon based on input focus
	if ($topRibbon.is(':visible')) {
		$searchBox.find('input').focus(function() {
			var ribbonMoveDistance = $topRibbon.outerWidth() - ($searchBox.offset().left - $topRibbon.offset().left) + 17;
			$topRibbon.stop().animate({marginRight:ribbonMoveDistance}, 1000);
		}).focusout(function() {
			$topRibbon.stop().animate({marginRight:0}, 1000);
		});
	}
	// Loading animation
	var siteURL = "http://" + top.location.host.toString(),
		$internalLinks = "a[href^='" + siteURL + "'], a[href^='/'], a[href^='./'], a[href^='../']";
	$('#out-shadow').on("click", $internalLinks, function() {
		$pageLoader.fadeIn(1500).delay(7000).fadeOut(1000);
	});
	$openFrame.on("click", function() {
		var urlFrame = $(this).attr('href');
		$pageLoader.append('<iframe id="frame1" src="' + urlFrame + '" frameborder="0" scrolling="auto"></iframe>').fadeIn(1500).on("click", function() {
			$(this).find('iframe, .atribusiform').remove();
			$(this).slideUp();
		});
		return false;
	});
	// Toggle PRE Tag
	$togglePre.on("change", function() {
		if ($(this).is(':checked')) {
			$body.addClass('prelight');
			createCookie('pre', 'prelight', 1000);
		} else {
			$body.removeClass('prelight');
			eraseCookie('pre', 'prelight');
		}
	});
	if (readCookie('pre')) {
		$body.addClass('prelight');
		$togglePre.prop('checked', true);
	}
	// Show/hide subscribe form
	$subscribeButton.on("click", function() {
		$topRibbon.stop().animate({
			width: 328
		}, 2000, "easeInOutExpo", function() {
			$subscribeForm.fadeIn('slow');
		});
		return false;
	});
	$closeForm.on("click", function() {
		$subscribeForm.fadeOut('slow', function() {
			$topRibbon.stop().animate({
				width: 108
			}, 1000, "easeInOutExpo");
		});
		return false;
	});
	// Accordion sidebar
	$sidebarWrapper.find('.widget-content').hide();
	$sidebarWrapper.find('h2').on("click", function() {
		$sidebarWrapper.find('h2').removeClass('headactive').next().slideUp(900, "easeInOutExpo");
		if ($(this).next().is(':hidden')) {
			$(this).addClass('headactive').next().slideDown(600, "easeInOutExpo");
		}
	}).last().addClass('headactive').next().show();
	// Label widget hover effect
	$labelWidget.find('a').hover(function() {
		$(this).find('.label-count').slideDown(500, "easeOutBounce");
	}, function() {
		$(this).find('.label-count').fadeOut(400, "easeOutQuart");
	});
	// Comments...
	$myComments.on("click", ".emo", function(e) {
		$('.emoKey').remove();
		$(this).after('<input type="text" size="6" class="emoKey" value=" '+this.alt+'" />');
		$('.emoKey').trigger("select");
		e.stopPropagation();
	}).find('.komentar-spam').each(function(allowLinks,commentContents) {
		allowLinks = $(this).find('a:not(.allow)');
		commentContents = $(this).html();
		txtContents = commentContents.replace(/<br>/ig, "\n").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/&lt;pre&gt;/ig, "&lt;i rel=\"pre\"&gt;").replace(/&lt;code&gt;/ig, "&lt;i rel=\"code\"&gt;").replace(/&lt;blockquote&gt;/ig, "&lt;b rel=\"quote\"&gt;").replace(/&lt;h([1-6])&gt;/ig, "&lt;b rel=\"h$1\"&gt;").replace(/&lt;\/(code|pre)&gt;/ig, "&lt;\/i&gt;").replace(/&lt;\/(blockquote|h[1-6])&gt;/ig, "&lt;\/b&gt;");
		if (allowLinks.length) {
			$(this).html('Your comments have been deleted/hidden for safety and comfort reasons other readers. This is most likely because you write a comment along with the emergence of the links that readers do not need/not in accordance with the discussion. But if not that, I hope you are willing to try to write your comments back without including the link/active link is not required. Here is a copy that you may need a new one of the older comments before you write this:<textarea spellcheck="false">' + txtContents + '</textarea>Thank you very much for your contribution on the blog this experiment. Regards, <strong>Administrator <big>&hearts;</big></strong><br>').addClass('deleted-by-js').closest('.cm_wrap').find('.cm_reply a').remove();
		}
	});
	// Comments manipulation
	var $commentImages = $('.incomment');
	$commentImages.each(function(link) {
		link = $(this).attr('src');
		$(this).wrap('<a class="center allow" href="'+link+'" target="_blank"></a>');
		$(this).attr('src', link.replace(/\/s(640|1600)/g, "/s400"));
	});
	tagReplace('b[rel="quote"]','<blockquote><p>','</p></blockquote>');
	tagReplace('i[rel="pre"]','<pre><code>','</code></pre>');
	var $codeRef = $('div > code,p > code,td > code');
	$codeRef.each(function() {
		$(this).wrapInner('<a class="allow" title="Browse the meaning of this code" href="/p/search.html?LDC=' + encodeURIComponent($(this).text()) + '" target="_blank"></a>');
	});
	$body.on("dblclick","pre code",function(){var ww=$window.width(),wh=$window.height(),ct=$(this).html().replace(/<br ?\/?>/g,"\n").replace(/<(.*?)>/g,""),w=window.open('','','width=400,height=250,top='+((wh/2)-125)+',left='+((ww/2)-200)+',scrollbars=0');w.document.write('<!DOCTYPE html><html><head><title>Source Code</title><style type="text/css">*{margin:0;padding:0}textarea{display:block;position:absolute;top:0;right:0;bottom:0;left:0;resize:none;border:none;width:100%;height:100%;background-color:white;color:black}</style></head><body><textarea>'+ct+'</textarea></body><scr'+'ipt type="text/javascript">var a=document.getElementsByTagName(\'textarea\')[0];a.focus();a.select();</scr'+'ipt></html>');});
	// Thread comment form
	var source = ($commentEditor.length) ? $commentEditor.attr('src').split('#') : "";
	$ansButton.on("click", function() {
		$alertBox.hide();
		$commentEditor.css('opacity',0);
		$ansButton.removeClass('clicked');
		$(this).addClass('clicked');
		var start = source[0], end = source[1],
			replyFrame = start + '&parentID=' + $(this).data('rel').substr(1) + '#' + end,
			$goTo = $(this).closest('.cm_wrap');
		$viewPort.scrollTop($goTo.offset().top - 30);
		$loadingText.html('<span>Loading...</span>');
		$commentForm.appendTo($goTo);
		$commentEditor.attr('src', replyFrame).on("load", function() {
			$(this).css('opacity', 1);
			$loadingText.html('');
		});
		return false;
	});
	$myComments.on("click", "#cancel-answer", function() {
		var ofs = $('#comment-editor-src').attr('href');
		$loadingText.html('<span>Loading...</span>');
		$commentForm.appendTo($myComments);
		$commentEditor.css('opacity', 0).attr('src', ofs + '#' + source[1]).on("load", function() {
			$(this).css('opacity', 1);
			$loadingText.html('');
		});
		$ansButton.removeClass('clicked');
		return false;
	});
	$fiddleScreen.each(function(url) {
		url = $(this).data('src');
		$(this).after('<iframe class="jsfiddle-demo center" src="' + url + '"></iframe>').remove();
	});
	// Toolpik
	$myDescription.hover(function(e) {
		var winWidth = $window.width(),
			winHeight = $window.height();
		$(this).append('<div id="toolpik"><div id="ldc"></div><div style="clear:both;"></div></div>');
		$('#ldc', '#toolpik').html($(this).attr('title'));
		$(this).removeAttr('title');
		var toolpikWidth = $("#toolpik").outerWidth(),
			toolpikHeight = $("#toolpik").outerHeight(),
			top = e.clientY - toolpikHeight / 2,
			left = e.clientX - toolpikWidth / 2;
		if (top + toolpikHeight > winHeight) {
			top = winHeight - toolpikHeight - 50;
		} else if (top <= 0) {
			top = 10;
		}
		if (left + toolpikWidth > winWidth) {
			left = winWidth - toolpikWidth - 50;
		} else if (left <= 0) {
			left = 10;
		}
		$('#toolpik').delay(600).fadeIn(1000, function() {
			$(this).delay(600).animate({top:top-70,left:left}, 2000, "easeOutBack", function() {
				$(this).animate({top:top}, 400);
			});
		});
	}, function() {
		$(this).attr('title', $('#ldc').html());
		$('#ldc').parent().remove();
	});
	// Update Board
	$blogStatus.hover(function() {
		$updateBoard.filter(':not(:animated)').delay(1000).show('slow', "easeOutBack");
	}, function() {
		$updateBoard.stop(true, true).delay(1000).hide('slow', "easeInExpo");
	});
	// Top link
	$window.on("scroll", function() {
		var scrollTop = $(this).scrollTop();
		if (scrollTop > 100) {
			$topLink.removeAttr('href');
			$topLink.stop().animate({bottom:0,right:0}, 600);
			$checkerBox.stop().animate({right:50}, 1000);
		} else {
			$topLink.stop().animate({bottom:-40,right:-40}, 600);
			$checkerBox.stop().animate({right:20}, 1000);
		}
	});
	$topLink.on("click", function() {
		$viewPort.stop().animate({scrollTop:0}, 970, "easeInOutQuad");
		return false;
	});
	// Drop down menu
	function onHover() {
		$nav.find('li').hover(function() {
			$('ul', this).filter(':not(:animated)').slideDown(600, "easeOutBounce").parent().addClass('active');
		}, function() {
			$('ul', this).slideUp(600, "easeInExpo").parent().removeClass('active');
		});
	} onHover();
	$nav.on("mouseleave", onHover).find('.hidden').removeClass('hidden').prev().on("click", function() {
		$(this).next().toggle().parent().toggleClass('active').off("hover");
		return false;
	});
	$jumpLink.on("click", function() {
		var distance = ($('#' + this.hash.substr(1)).length) ? $('#' + this.hash.substr(1)).offset().top : $('.' + this.hash.substr(1)).first().offset().top;
		$viewPort.animate({scrollTop:distance-30}, 'slow');
		return false;
	});
	if (!readCookie('disable-notification')) {
		$loadingText.html('<iframe style="display:block;position:absolute;top:0;left:50%;width:66px;height:17px;border:none;background:transparent;overflow:hidden;margin:2px auto 0 -33px;" src="http://ldctutorial.googlecode.com/svn/trunk/personal/notification-feed.html"></iframe>');
	}
	// Preloading...
	var urlHash = (window.location.hash) ? window.location.hash.substr(1) : '';
	$window.on("load", function() {
		// Fix my comment jump links bug!
		if(window.location.hash && window.location.hash.indexOf('#c') !== -1) {
			var $targetElem = $('.' + urlHash),
				scrollDistance = $targetElem.offset().top - 30;
			$viewPort.animate({scrollTop:scrollDistance}, 4000, function() {
				$targetElem.find('.cm_entry').css('border','2px solid yellow');
				$targetElem.find('.avatar-image-container').css({'padding':0,'border':'5px solid yellow'});
			});
		}
		$commentVideo.each(function() {
			if(/youtube\.com\/embed/.test($(this).data('src'))) {
				$(this).attr('src', $(this).data('src'));
			} else {
				$(this).removeAttr('src').css('background','#900 url(http://hompimpa.googlecode.com/svn/trunk/personal/images/iframe-fallback.png) no-repeat 50% 50%');
			}
		});
	});
} allStuff();